<template>
	<view class="container">
		<view class="logo">
			<image src="/static/basicprofile.png" mode="aspectFit" class="logo-img"></image>
		</view>

		<button type="primary" open-type="getUserInfo" @getuserinfo="onGetUserInfo"
			class="login-btn flex-row items-center">
			<view style="display: inline-block; padding-right: 4px;"><u-icon name="weixin-fill" color="#fff"
					size="30"></u-icon></view>
			微信一键登录
		</button>

		<!-- <view class="policy">
			<navigator url="/pages/userAgreement/userAgreement" hover-class="none">
				用户协议
			</navigator>
			<text> | </text>
			<navigator url="/pages/privacyPolicy/privacyPolicy" hover-class="none">
				隐私政策
			</navigator>
		</view> -->
	</view>
</template>

<script>
	import {
		wechatLogin
	} from '@/api/weChat_login.js';

	export default {
		data() {
			return {
				redirectUrl: ""
			};
		},
		onLoad(options) {
			if (options.redirect) {
				this.redirectUrl = decodeURIComponent(options.redirect);
			}
		},
		methods: {
			onGetUserInfo(e) {
				if (e.mp.detail.userInfo) {
					const that = this;
					const userInfo = e.mp.detail.userInfo;

					uni.showLoading({
						title: '请稍后...'
					})

					// 获取code
					uni.login({
						provider: 'weixin',
						success: function(loginRes) {
							that.login(loginRes.code, userInfo);
						}
					});
				} else {
					uni.$u.toast('授权失败');
				}
			},
			login(code, userInfo) {
				wechatLogin({
						code: code,
						nickname: userInfo.nickname,
						avatar: userInfo.avatar,
					})
					.then(res => {
						uni.hideLoading();
						const userinfo = res.data.userinfo;
						const inviter = res.data.inviter;
						uni.setStorageSync('inviter', inviter);
						uni.setStorageSync('userInfo', userinfo);
						uni.setStorageSync('token', userinfo.token);
						uni.$u.toast('登录成功');
						
						setTimeout(() => {
							if (this.redirectUrl) {
								uni.redirectTo({
									url: this.redirectUrl
								})
							} else {
								uni.switchTab({
									url: '/pages/index/index' // 登录成功跳转首页
								});
							}
						}, 800);
					})
					.catch(err => {
						uni.hideLoading();
						console.error('失败:', err);
					});
			}
		}
	};
</script>

<style scoped>
	.container {
		padding: 40rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		height: 90vh;
	}

	.logo-img {
		width: 180rpx;
		height: 180rpx;
		border-radius: 100rpx;
		margin-bottom: 80rpx;
	}

	.login-btn {
		justify-content: center;
		width: 80%;
		border-radius: 120rpx;
		background-image: linear-gradient(90deg, #007aff 50%, #569be7 100%);
		box-shadow: 2px 2px 10px #b1c8ff;
		color: white;
		margin-bottom: 40rpx;
	}

	.policy {
		font-size: 24rpx;
		color: #999;
	}
</style>